// app.js
// 只看routes部分
const Koa = require('koa')
const app = new Koa()
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const token = require('./other/token');

// const index = require('./routes/index')
const users = require('./routes/user')
const admin = require('./routes/admin');
const home = require('./routes/home')
const file = require('./routes/file');
const inspect = require('./routes/inspect');
const statistics = require('./routes/statistics');



// error handler
onerror(app)

// middlewares
app.use(bodyparser({
    enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))
app.use(token.tokenvalidate);

// logger
app.use(async (ctx, next) => {
    const start = new Date()
    await next()
    const ms = new Date() - start
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

app.use(async (ctx, next) => {
    try {
        await next()
    } catch (error) {
        ctx.status = 500;
        ctx.body = {
            errno: error.errno,
            code: error.code,
            sqlMessage: error.sqlMessage,
            message: error.message
        }
    }
})

app.use(users.routes(), users.allowedMethods())
app.use(admin.routes(), admin.allowedMethods())
app.use(home.routes(), home.allowedMethods())
app.use(inspect.routes(), inspect.allowedMethods())
app.use(statistics.routes(), statistics.allowedMethods())
app.use(file.routes(), file.allowedMethods())


app.listen(3000);


